"use client";

import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import dayjs from 'dayjs';
import ComponentCard from '@/components/common/ComponentCard';
import PageBreadcrumb from '@/components/common/PageBreadCrumb';
import { useToast } from '@/context/ToastContext';

interface ChainConfig {
  id: number;
  chain: string;
  isEnabled: boolean;
  rpcUrl: string;
  wssUrl?: string;
  minValueUsd: number;
  blockTime: number;
  maxRetries: number;
  requestDelay: number;
  batchSize: number;
  fallbackRpcs?: string[];
  chainSettings?: any;
  lastStarted?: string;
  lastStopped?: string;
  errorCount: number;
  totalTxCount: number;
  createdAt: string;
  updatedAt: string;
}

interface MonitoringStatus {
  isRunning: boolean;
  activeChains: number;
  totalChains: number;
  chains: Record<string, any>;
}

interface SystemStatus {
  servicesReady: boolean;
  monitoring: MonitoringStatus;
  environment: {
    nodeEnv: string;
    autoStartEnabled: boolean;
  };
  timestamp: string;
}

const Monitor: React.FC = () => {
  const [systemStatus, setSystemStatus] = useState<SystemStatus | null>(null);
  const [chainConfigs, setChainConfigs] = useState<ChainConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [globalActionLoading, setGlobalActionLoading] = useState<string | null>(null);
  const [editingConfig, setEditingConfig] = useState<ChainConfig | null>(null);
  const [showConfigModal, setShowConfigModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [statusFetching, setStatusFetching] = useState(false);
  const { addToast } = useToast();

  // 使用useRef来跟踪最新的状态值，避免定时器闭包问题
  const globalActionLoadingRef = useRef(globalActionLoading);
  const statusFetchingRef = useRef(statusFetching);
  
  // 更新ref的值
  useEffect(() => {
    globalActionLoadingRef.current = globalActionLoading;
  }, [globalActionLoading]);
  
  useEffect(() => {
    statusFetchingRef.current = statusFetching;
  }, [statusFetching]);

  // Fetch monitoring status with retry logic
  const fetchMonitoringStatus = async (retries = 2) => {
    if (statusFetchingRef.current) return; // 防止并发调用
    
    try {
      statusFetchingRef.current = true;
      const response = await axios.get('/api/admin/monitoring/status', { timeout: 15000 });
      if (response.data.success) {
        setSystemStatus(response.data);
        setError(null);
      } else {
        setError(response.data.error || 'Failed to fetch monitoring status');
      }
    } catch (err) {
      let errorMessage = '';
      
      if (axios.isAxiosError(err)) {
        if (err.code === 'ECONNABORTED') {
          // 超时重试
          if (retries > 0) {
            console.log(`Status fetch timeout, retrying... (${retries} attempts left)`);
            setTimeout(() => fetchMonitoringStatus(retries - 1), 2000);
            return;
          }
          errorMessage = 'Status request timeout - services may be initializing';
        } else if (err.response?.status === 503) {
          // 在开发环境中，503是正常状态（服务未启动），不显示错误
          if (process.env.NODE_ENV === 'development') {
            setError(null);
            return;
          } else {
            errorMessage = 'Services are starting up - please wait a moment';
          }
        } else if (err.response?.data?.error) {
          errorMessage = err.response.data.error;
        } else {
          errorMessage = err.message;
        }
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      
      if (errorMessage) {
        setError(errorMessage);
      } else {
        setError(null);
      }
      console.error('Monitoring status fetch error:', err);
    } finally {
      statusFetchingRef.current = false;
    }
  };

  // Fetch chain configurations
  const fetchChainConfigs = async () => {
    try {
      const response = await axios.get('/api/config/chains', { timeout: 10000 });
      if (response.data.success) {
        setChainConfigs(response.data.data);
      }
    } catch (err) {
      console.error('Chain configs fetch error:', err);
    }
  };

  // Start monitoring manually
  const startMonitoring = async () => {
    setGlobalActionLoading('start-all');
    
    try {
      // 增加超时时间，因为首次启动可能需要初始化服务
      const response = await axios.post('/api/admin/monitoring/start', {}, { timeout: 60000 });
      
      if (response.data.success) {
        addToast({
          type: 'success',
          title: 'Start Successful',
          message: response.data.message || 'Monitoring service started successfully',
          duration: 4000
        });
        
        // 智能状态刷新：立即刷新一次，然后间隔刷新直到稳定
        const refreshStatus = async (attempts = 0, maxAttempts = 5) => {
          try {
            await fetchMonitoringStatus(0); // 不重试，避免延迟
            
            // 继续刷新直到达到最大尝试次数
            if (attempts < maxAttempts) {
              setTimeout(() => refreshStatus(attempts + 1, maxAttempts), 1000 * (attempts + 1));
            }
          } catch (statusError) {
            console.warn(`Status refresh attempt ${attempts + 1} failed:`, statusError);
            if (attempts < maxAttempts) {
              setTimeout(() => refreshStatus(attempts + 1, maxAttempts), 2000);
            }
          }
        };
        
        refreshStatus();
      } else {
        addToast({
          type: 'error',
          title: 'Start Failed', 
          message: response.data.error || response.data.message || 'Failed to start monitoring',
          duration: 6000
        });
      }
    } catch (err) {
      let errorMsg = 'Failed to start monitoring';
      
      if (axios.isAxiosError(err)) {
        if (err.code === 'ECONNABORTED') {
          errorMsg = 'Request timeout - startup may still be in progress. Please check status in a moment.';
        } else if (err.response?.data?.details) {
          errorMsg = err.response.data.details;
        } else if (err.response?.data?.error) {
          errorMsg = err.response.data.error;
        } else if (err.response?.data?.message) {
          errorMsg = err.response.data.message;
        } else {
          errorMsg = err.message;
        }
      } else if (err instanceof Error) {
        errorMsg = err.message;
      }
      
      addToast({
        type: 'error',
        title: 'Start Failed',
        message: errorMsg,
        duration: 8000
      });
      
      console.error('Start monitoring error:', err);
    } finally {
      setGlobalActionLoading(null);
    }
  };

  // Stop monitoring
  const stopMonitoring = async () => {
    setGlobalActionLoading('stop-all');
    
    try {
      const response = await axios.post('/api/admin/monitoring/stop', {}, { timeout: 30000 });
      
      if (response.data.success) {
        addToast({
          type: 'success',
          title: 'Stop Successful',
          message: response.data.message || 'Monitoring service stopped',
          duration: 4000
        });
        
        // 延迟一下再刷新状态，确保服务完全停止
        setTimeout(async () => {
          try {
            await fetchMonitoringStatus();
          } catch (statusError) {
            console.warn('Failed to refresh status after stop:', statusError);
          }
        }, 1000);
      } else {
        addToast({
          type: 'error',
          title: 'Stop Failed',
          message: response.data.error || response.data.message || 'Failed to stop monitoring',
          duration: 6000
        });
      }
    } catch (err) {
      let errorMsg = 'Failed to stop monitoring';
      
      if (axios.isAxiosError(err)) {
        if (err.code === 'ECONNABORTED') {
          errorMsg = 'Request timeout - stop operation may still be in progress';
        } else if (err.response?.data?.details) {
          errorMsg = err.response.data.details;
        } else if (err.response?.data?.error) {
          errorMsg = err.response.data.error;
        } else {
          errorMsg = err.message;
        }
      } else if (err instanceof Error) {
        errorMsg = err.message;
      }
      
      addToast({
        type: 'error',
        title: 'Stop Failed',
        message: errorMsg,
        duration: 6000
      });
      
      console.error('Stop monitoring error:', err);
    } finally {
      setGlobalActionLoading(null);
    }
  };

  // Save chain configuration
  const handleSaveConfig = async (config: ChainConfig) => {
    try {
      setSaving(true);
      const response = await axios.post('/api/config/chains', {
        chain: config.chain,
        config: {
          isEnabled: config.isEnabled,
          rpcUrl: config.rpcUrl,
          wssUrl: config.wssUrl,
          minValueUsd: config.minValueUsd,
          blockTime: config.blockTime,
          maxRetries: config.maxRetries,
          requestDelay: config.requestDelay,
          batchSize: config.batchSize,
          fallbackRpcs: config.fallbackRpcs,
          chainSettings: config.chainSettings
        }
      });
      
      if (response.data.success) {
        addToast({
          type: 'success',
          title: 'Configuration Saved',
          message: `${getChainName(config.chain)} configuration updated successfully`,
          duration: 4000
        });
        await fetchChainConfigs();
        setShowConfigModal(false);
        setEditingConfig(null);
      } else {
        addToast({
          type: 'error',
          title: 'Save Failed',
          message: response.data.error || 'Failed to save configuration',
          duration: 6000
        });
      }
    } catch (error) {
      addToast({
        type: 'error',
        title: 'Save Failed',
        message: error instanceof Error ? error.message : 'Unknown error',
        duration: 6000
      });
      console.error('Failed to save configuration:', error);
    } finally {
      setSaving(false);
    }
  };

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        await Promise.all([
          fetchMonitoringStatus(),
          fetchChainConfigs()
        ]);
      } catch (err) {
        // 在开发环境中，初始加载失败是正常的（服务未启动）
        if (process.env.NODE_ENV === 'development') {
          console.log('Initial load in development environment - services not started yet');
        } else {
          console.error('Initial load failed:', err);
        }
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []); // 只在组件挂载时执行一次

  // 单独的useEffect用于自动刷新，避免依赖状态变化导致重复创建定时器
  useEffect(() => {
    const interval = setInterval(() => {
      // 只有在没有正在进行操作且没有正在获取状态时才自动刷新
      if (!globalActionLoadingRef.current && !statusFetchingRef.current) {
        fetchMonitoringStatus(0); // 自动刷新不重试，避免延迟
      }
    }, 30000); // 30秒间隔

    return () => {
      clearInterval(interval);
    };
  }, []); // 空依赖数组，只创建一次定时器

  const getStatusColor = (status: string, isActive: boolean) => {
    if (status === 'starting' || status === 'stopping') return 'bg-yellow-500';
    if (status === 'error') return 'bg-red-500';
    return isActive ? 'bg-green-500' : 'bg-gray-500';
  };

  const getChainIcon = (chain: string) => {
    const icons: Record<string, string> = {
      ethereum: '🔷',
      bsc: '🟡',
      bitcoin: '🟠',
      base: '🔵',
      polygon: '🟣',
      solana: '🟢'
    };
    return icons[chain] || '⚪';
  };

  const getChainName = (chain: string) => {
    const names: Record<string, string> = {
      ethereum: 'Ethereum',
      bsc: 'BSC',
      bitcoin: 'Bitcoin',
      base: 'Base',
      polygon: 'Polygon',
      solana: 'Solana'
    };
    return names[chain] || chain.charAt(0).toUpperCase() + chain.slice(1);
  };

  const openConfigModal = (config: ChainConfig) => {
    setEditingConfig({ ...config });
    setShowConfigModal(true);
  };

  const updateEditingConfig = (field: keyof ChainConfig, value: any) => {
    if (!editingConfig) return;
    setEditingConfig({
      ...editingConfig,
      [field]: value
    });
  };

  const updateFallbackRpcs = (index: number, value: string) => {
    if (!editingConfig) return;
    const fallbackRpcs = [...(editingConfig.fallbackRpcs || [])];
    fallbackRpcs[index] = value;
    setEditingConfig({
      ...editingConfig,
      fallbackRpcs
    });
  };

  const addFallbackRpc = () => {
    if (!editingConfig) return;
    setEditingConfig({
      ...editingConfig,
      fallbackRpcs: [...(editingConfig.fallbackRpcs || []), '']
    });
  };

  const removeFallbackRpc = (index: number) => {
    if (!editingConfig) return;
    const fallbackRpcs = [...(editingConfig.fallbackRpcs || [])];
    fallbackRpcs.splice(index, 1);
    setEditingConfig({
      ...editingConfig,
      fallbackRpcs
    });
  };

  if (loading) {
    return (
      <div>
        <PageBreadcrumb pageTitle="Blockchain Monitor" />
        <div className="space-y-6">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] p-6">
              <div className="animate-pulse">
                <div className="h-4 bg-gray-300 dark:bg-gray-600 rounded mb-4"></div>
                <div className="h-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div>
      <PageBreadcrumb pageTitle="Blockchain Monitor" />
      
      <div className="space-y-6">
        {/* Page Header */}
        <div className="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03] p-6">
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">Blockchain Monitoring Center</h1>
              <p className="text-gray-600 dark:text-gray-400">Real-time monitoring of multi-chain transactions and system status</p>
            </div>
          </div>
        </div>

        {error && (
          <div className="p-4 text-red-700 bg-red-100 border border-red-300 rounded-2xl dark:bg-red-900/20 dark:text-red-200 dark:border-red-600">
            <p className="font-medium">System Error</p>
            <p className="text-sm">{error}</p>
          </div>
        )}

        {/* Global Control - Always show for manual initialization */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <ComponentCard title="Global Control">
            <div className="space-y-2">
              <button
                onClick={startMonitoring}
                disabled={globalActionLoading === 'start-all'}
                className="w-full bg-green-600 hover:bg-green-700 text-white px-3 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {globalActionLoading === 'start-all' ? 'Starting...' : 'Start All Monitoring'}
              </button>
              <button
                onClick={stopMonitoring}
                disabled={globalActionLoading === 'stop-all'}
                className="w-full bg-red-600 hover:bg-red-700 text-white px-3 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {globalActionLoading === 'stop-all' ? 'Stopping...' : 'Stop All Monitoring'}
              </button>
            </div>
          </ComponentCard>
          
          {/* Service Status - Show basic info even when error */}
          <ComponentCard title="Service Status">
            <div className="space-y-3">
              {systemStatus ? (
                <>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600 dark:text-gray-400">Services Ready:</span>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      systemStatus.servicesReady 
                        ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' 
                        : 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400'
                    }`}>
                      {systemStatus.servicesReady ? 'Ready' : 'Not Ready'}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600 dark:text-gray-400">Environment:</span>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      {systemStatus.environment.nodeEnv}
                    </span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-gray-600 dark:text-gray-400">Auto Start:</span>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      {systemStatus.environment.autoStartEnabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </div>
                </>
              ) : (
                <div className="text-center text-gray-500 dark:text-gray-400">
                  <p className="text-sm">Ready to start monitoring</p>
                  <p className="text-xs mt-2">Click "Start All Monitoring" to initialize services and begin monitoring</p>
                </div>
              )}
            </div>
          </ComponentCard>

          <ComponentCard title="System Info">
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">Version:</span>
                <span className="text-sm font-medium text-gray-900 dark:text-white">v2.0</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-gray-600 dark:text-gray-400">Mode:</span>
                <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
                  Development
                </span>
              </div>
            </div>
          </ComponentCard>
        </div>

        {/* System Overview - Only show when status is available */}
        {systemStatus && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <ComponentCard title="Monitoring Status">
              <div className="space-y-3">
                <div className="flex justify-between items-center">
                  <span className="text-gray-600 dark:text-gray-400">Running:</span>
                  <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                    systemStatus.monitoring.isRunning 
                      ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' 
                      : 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400'
                  }`}>
                    {systemStatus.monitoring.isRunning ? 'Running' : 'Stopped'}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600 dark:text-gray-400">Active Chains:</span>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">
                    {systemStatus.monitoring.activeChains}/{systemStatus.monitoring.totalChains}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600 dark:text-gray-400">Last Update:</span>
                  <span className="text-xs text-gray-600 dark:text-gray-400">
                    {dayjs(systemStatus.timestamp).format('HH:mm:ss')}
                  </span>
                </div>
              </div>
            </ComponentCard>
          </div>
        )}

        {/* Chain Configuration Management */}
        <div className="space-y-4">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-bold text-gray-900 dark:text-white">Chain Configurations</h2>
            <div className="text-sm text-gray-600 dark:text-gray-400">
              Manage blockchain monitoring configurations. Global start/stop controls all enabled chains.
            </div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {chainConfigs.map(config => {
              const chainStatus = systemStatus?.monitoring.chains[config.chain];
              const isCurrentlyRunning = chainStatus?.isActive && chainStatus?.status === 'running';
              
              return (
                <ComponentCard key={config.chain} title={`${getChainIcon(config.chain)} ${getChainName(config.chain)}`}>
                  <div className="space-y-4">
                    {/* Configuration Status */}
                    <div className="space-y-3">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Database Status:</span>
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                          config.isEnabled 
                            ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' 
                            : 'bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400'
                        }`}>
                          {config.isEnabled ? 'Enabled' : 'Disabled'}
                        </span>
                      </div>
                      
                      {systemStatus && (
                        <div className="flex justify-between items-center">
                          <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Runtime Status:</span>
                          <div className="flex items-center gap-2">
                            <div className={`w-2 h-2 rounded-full ${
                              isCurrentlyRunning ? 'bg-green-500' : 
                              chainStatus?.status === 'error' ? 'bg-red-500' : 'bg-gray-400'
                            }`}></div>
                            <span className="text-xs text-gray-600 dark:text-gray-400">
                              {isCurrentlyRunning ? 'Running' : 
                               chainStatus?.status === 'error' ? 'Error' : 'Stopped'}
                            </span>
                          </div>
                        </div>
                      )}
                      
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Min Amount:</span>
                        <span className="text-sm text-gray-900 dark:text-white">
                          ${config.minValueUsd.toLocaleString()}
                        </span>
                      </div>
                      
                      {chainStatus && (
                        <>
                          <div className="flex justify-between items-center">
                            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Transactions:</span>
                            <span className="text-sm text-gray-900 dark:text-white">
                              {(chainStatus.totalTransactions || 0).toLocaleString()}
                            </span>
                          </div>
                          
                          <div className="flex justify-between items-center">
                            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Errors:</span>
                            <span className="text-sm text-gray-900 dark:text-white">
                              {chainStatus.errorCount || 0}
                            </span>
                          </div>
                          
                          {chainStatus.lastActivity && (
                            <div className="flex justify-between items-center">
                              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Last Activity:</span>
                              <span className="text-xs text-gray-600 dark:text-gray-400">
                                {dayjs(chainStatus.lastActivity).format('HH:mm:ss')}
                              </span>
                            </div>
                          )}
                        </>
                      )}
                    </div>

                    {/* Configuration Management */}
                    <div className="pt-3 border-t border-gray-200 dark:border-gray-700">
                      <button 
                        onClick={() => openConfigModal(config)}
                        className="w-full bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded text-sm font-medium transition-colors"
                      >
                        ⚙️ Edit Configuration
                      </button>
                    </div>

                    {/* Technical Details */}
                    <div className="text-xs text-gray-600 dark:text-gray-400 space-y-1">
                      <div className="truncate">RPC: {config.rpcUrl}</div>
                      <div>Block Time: {config.blockTime}ms</div>
                      <div>Batch Size: {config.batchSize}</div>
                    </div>
                  </div>
                </ComponentCard>
              );
            })}
          </div>
        </div>

        {/* Configuration Modal */}
        {showConfigModal && editingConfig && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-xl font-bold text-gray-900 dark:text-white">
                  Configure {getChainIcon(editingConfig.chain)} {getChainName(editingConfig.chain)}
                </h2>
                <button
                  onClick={() => setShowConfigModal(false)}
                  className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* Important Notice */}
              <div className="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg">
                <div className="flex items-start gap-3">
                  <svg className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                  </svg>
                  <div>
                    <h3 className="text-sm font-medium text-blue-900 dark:text-blue-100">Configuration Info</h3>
                    <p className="text-sm text-blue-700 dark:text-blue-300 mt-1">
                      Use the "Enabled" setting to control whether this chain participates in monitoring. 
                      Global start/stop will only affect enabled chains.
                    </p>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* Monitoring Control */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Monitoring Control</h3>
                  
                  {/* Enabled Toggle - Most Important */}
                  <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600">
                    <label className="flex items-center justify-between">
                      <div>
                        <span className="text-base font-medium text-gray-900 dark:text-white">Enable Monitoring</span>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                          Controls whether this chain is included in global monitoring operations
                        </p>
                      </div>
                      <div className="ml-4">
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={editingConfig.isEnabled}
                            onChange={(e) => updateEditingConfig('isEnabled', e.target.checked)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                        </label>
                      </div>
                    </label>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Minimum Value USD
                    </label>
                    <input
                      type="number"
                      value={editingConfig.minValueUsd}
                      onChange={(e) => updateEditingConfig('minValueUsd', parseFloat(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="5000"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Block Time (ms)
                    </label>
                    <input
                      type="number"
                      value={editingConfig.blockTime}
                      onChange={(e) => updateEditingConfig('blockTime', parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="15000"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Max Retries
                    </label>
                    <input
                      type="number"
                      value={editingConfig.maxRetries}
                      onChange={(e) => updateEditingConfig('maxRetries', parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="3"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Request Delay (ms)
                    </label>
                    <input
                      type="number"
                      value={editingConfig.requestDelay}
                      onChange={(e) => updateEditingConfig('requestDelay', parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="1000"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Batch Size
                    </label>
                    <input
                      type="number"
                      value={editingConfig.batchSize}
                      onChange={(e) => updateEditingConfig('batchSize', parseInt(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="100"
                    />
                  </div>
                </div>

                {/* Network Settings */}
                <div className="space-y-4">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Network Settings</h3>
                  
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Primary RPC URL
                    </label>
                    <input
                      type="text"
                      value={editingConfig.rpcUrl}
                      onChange={(e) => updateEditingConfig('rpcUrl', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="https://..."
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      WebSocket URL (Optional)
                    </label>
                    <input
                      type="text"
                      value={editingConfig.wssUrl || ''}
                      onChange={(e) => updateEditingConfig('wssUrl', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                      placeholder="wss://..."
                    />
                  </div>

                  <div>
                    <div className="flex justify-between items-center mb-2">
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Fallback RPC URLs
                      </label>
                      <button
                        onClick={addFallbackRpc}
                        className="text-blue-600 hover:text-blue-700 text-sm font-medium"
                      >
                        + Add
                      </button>
                    </div>
                    <div className="space-y-2">
                      {(editingConfig.fallbackRpcs || []).map((rpc, index) => (
                        <div key={index} className="flex gap-2">
                          <input
                            type="text"
                            value={rpc}
                            onChange={(e) => updateFallbackRpcs(index, e.target.value)}
                            className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                            placeholder="https://..."
                          />
                          <button
                            onClick={() => removeFallbackRpc(index)}
                            className="text-red-600 hover:text-red-700 px-2"
                          >
                            ×
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              {/* Modal Actions */}
              <div className="flex justify-end gap-4 mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                <button
                  onClick={() => setShowConfigModal(false)}
                  className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg text-sm font-medium transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => handleSaveConfig(editingConfig)}
                  disabled={saving}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {saving ? 'Saving...' : 'Save Configuration'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Last Updated */}
        {systemStatus && (
          <div className="text-center text-gray-500 dark:text-gray-400 text-sm">
            Last Updated: {dayjs(systemStatus.timestamp).format('YYYY-MM-DD HH:mm:ss')}
          </div>
        )}
      </div>
    </div>
  );
};

export default Monitor; 